#!/bin/bash

. $LKP_SRC/lib/git.sh

pre_download()
{
	:
}

download()
{
	pre_download
	for url in $WEB_URL
	do
		wget -t 3 -T 10 --no-clobber $url && break
	done
	[[ $source_package ]] || source_package=$(basename $url)
	[[ $source_dir     ]] || source_dir=${source_package%%.tar.*}
	[[ $source_dir     ]] || source_dir=${source_package%%.tgz}
	[[ -d $source_dir ]] ||
	tar xf "$source_package"
}

patch_source()
{
	local PATCH=$LKP_SRC/pack/${BM_NAME}.patch
	[[ -f $PATCH ]] || return 0
	patch -p1 < $PATCH
}

build()
{
	patch_source || return
	[[ -x "./configure" ]] && ./configure $CONFIGURE_FLAGS
	if [[ -f 'Makefile' ]]; then
		make
	fi
}

install()
{
	if [[ -f 'Makefile' ]]; then
		make install-exec
	fi
}

strip_object_files()
{
	# Strip only debug information, so perf-report can still
	# output meaningful information
	[[ -d "/lkp/benchmarks/$BM_NAME" ]] &&
	find /lkp/benchmarks/$BM_NAME/ -type f -executable -size +10k \
	  \( ! -name "*.awk" -a ! -name "*.pl" -a ! -name "*.sh" -a ! -name "*.rb" -a ! -name "*.py" \) | xargs strip -d &> /dev/null
}

pack_deb()
{
	mkdir -p /tmp/$pkg_name/$BM_ROOT
	cp -af $BM_ROOT /tmp/$pkg_name/lkp/benchmarks
	mkdir -p /tmp/$pkg_name/DEBIAN
	cat > /tmp/$pkg_name/DEBIAN/control <<-EOF
	Package: $pkg_name
	Version: $(date +%F)
	Architecture: all
	Maintainer: LKP
	Description: LKP dependent packages
	EOF

	cd /tmp || return
	dpkg-deb --build $pkg_name
}

pack_rpm()
{
	mkdir -p $BUILD_DIR/$pkg_name/{BUILD,RPMS,S{OURCE,PEC,RPM}S}
	cat > $BUILD_DIR/$pkg_name/SPECS/$pkg_name.spec <<-EOF
	Name: $pkg_name
	Version: 1
	License: None
	Packager: LKP
	Release: 1
	Summary: LKP dependent packages

	%description
	LKP benchmarks rpm package

	%install
	# create directories where the files will be located
	mkdir -p \$RPM_BUILD_ROOT/$BM_ROOT
	# put the files in the relevant directories
	cp -a $BM_ROOT/* \$RPM_BUILD_ROOT/$BM_ROOT

	%files
	%defattr(-,root,root)
	$BM_ROOT/*
	EOF

	cat > $BUILD_DIR/$pkg_name/.rpmmacros <<-EOF
	%_topdir $BUILD_DIR/$pkg_name
	%_rpmfilename %%{NAME}.%%{ARCH}.rpm
	EOF

	(
		export HOME=$BUILD_DIR/$pkg_name
		rpmbuild -bb --verbose $BUILD_DIR/$pkg_name/SPECS/$pkg_name.spec
	)
}

pack()
{
	{
		echo /lkp
		echo /lkp/benchmarks
		echo /lkp/benchmarks/$BM_NAME
		find /lkp/benchmarks/$BM_NAME/*
	} |
	cpio --quiet -o -H newc --owner=root.root | gzip -n -9 > /lkp/benchmarks/${BM_NAME}.cgz
	[[ $arch ]] && mv "/lkp/benchmarks/${BM_NAME}.cgz" "/lkp/benchmarks/${BM_NAME}-${arch}.cgz"
}

pack_pkg()
{
	local distro=$1
	local pkg_name="${BM_NAME//_/-}-LKP"

	rm -fr "/tmp/$pkg_name"
	rm -fr "${BUILD_DIR:?}/$pkg_name" || return

	if [[ "$BM_NAME" != "lkp-src" ]]; then
		[[  "$(ls -A $BM_ROOT)" ]] || return 0
	fi

	case $distro in
		debian|ubuntu)
			pack_deb ;;
		fedora)
			pack_rpm ;;
		*)
			pack ;;
	esac
}

post_cleanup()
{
	:
}

cleanup()
{
	[[ $source_package ]] && {
		rm -f  "${BUILD_DIR:?}/${source_package}" || return
	}
	[[ $source_dir     ]] && {
		rm -fr "${BUILD_DIR:?}/${source_dir}" || return
	}
	post_cleanup
}
